package com.example.ktdemo.vpgallery.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;

import java.io.Serializable;

/**
 * FileName: BlurUtils
 * Author: lzt
 * Date: 2023/5/10 10:17
 */
public class VPBlurUtils implements Serializable {

    public static Bitmap blur(Context context, int blurRadius, Bitmap srcBitmap) {
        try {
            float radius = Math.min(25, blurRadius);
            radius = Math.max(0, radius);
            Bitmap bitmap = srcBitmap.copy(srcBitmap.getConfig(), true);
            final RenderScript rs = RenderScript.create(context);
            final Allocation input = Allocation.createFromBitmap(rs, srcBitmap,
                    Allocation.MipmapControl.MIPMAP_NONE,
                    Allocation.USAGE_SCRIPT);
            final Allocation output = Allocation.createTyped(rs, input.getType());
            final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
            script.setRadius(radius /* e.g. 3.f */);
            script.setInput(input);
            script.forEach(output);
            output.copyTo(bitmap);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return srcBitmap;
        }
    }
}
